package com.hw.blog.common;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 설정사항에 관련된 유틸리티 클래스
 * @version 1.0
 * @since   2012.06.27
 * @author  eyoh
 */
public class ConfigUtil {
	
	private String passKey = null;
	
	static Log logger = LogFactory.getLog(ConfigUtil.class);

    //public static String CONFIG_FILE = "/config.properties";

    private static Properties config;
    
    private ConfigUtil() {}

    private static void loadConfig() throws Exception {
 
        try {
        	
        	if (config==null) {
        		/*
	        	ClassLoader loader = Thread.currentThread().getContextClassLoader();
	    		InputStream in = null;
	    	    if (loader != null) in = loader.getResourceAsStream(CONFIG_FILE);
	    	    if (in == null) in = ClassLoader.getSystemResourceAsStream(CONFIG_FILE);
	
	    	    Properties pro = new Properties();
	    	    pro.load(in);
				in.close();
	
	            config = pro;
	            */
        		String config_file = ServerConfig.getHome() + "/conf/app.properties";
    			config = new Properties();
                config.load(new BufferedInputStream(new FileInputStream(config_file)));
                
                logger.info("Config file load = " + config_file );
        	}
        }
        catch (Exception e) {
        	//e.printStackTrace();
        	logger.error(e.toString(), e);
        }
    }

    public static Properties getConfig() throws Exception {
        if (config == null) {
            loadConfig();
        }
        return config;
    }

    public static String get(String key) throws Exception {
    	
    	if ( config == null ) {
            loadConfig();
        }
        if ( key == null ) {
            throw new Exception("Config Exception : key can not be null");
        }
        
        String value =  StringUtil.uniToEucKr( config.getProperty(key) );
        if (value != null) {
        	value.trim();
        }

        return value;
    }

    public static void set(String key, String value) throws Exception {
        if (config == null) {
            loadConfig();
        }
        if (key == null || value == null) {
            throw new Exception("Config Exception : key and value can not be null");
        }
        config.setProperty(key, value);
    }

	public String getPassKey() {
		return passKey;
	}

	public void setPassKey(String passKey) {
		this.passKey = passKey;
	}
    
}
